from typing import Dict, Any, List
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from app import logger
from flask import current_app
import json

class NotificationService:
    @staticmethod
    def notify(event: str, data: Dict[str, Any]) -> None:
        """发送通知"""
        if not current_app.config['NOTIFICATION']['enabled']:
            return

        methods = current_app.config['NOTIFICATION']['methods']
        for method in methods:
            if event in method['events']:
                if method['type'] == 'webhook':
                    NotificationService._send_webhook(method['url'], event, data)
                elif method['type'] == 'email':
                    NotificationService._send_email(method, event, data)

    @staticmethod
    def _send_webhook(url: str, event: str, data: Dict[str, Any]) -> None:
        """发送webhook通知"""
        try:
            payload = {
                'event': event,
                'data': data
            }
            response = requests.post(url, json=payload, timeout=5)
            response.raise_for_status()
        except Exception as e:
            logger.error(f"Webhook notification failed: {str(e)}")

    @staticmethod
    def _send_email(config: Dict[str, Any], event: str, data: Dict[str, Any]) -> None:
        """发送邮件通知"""
        try:
            msg = MIMEMultipart()
            msg['From'] = config['from_email']
            msg['To'] = ', '.join(config['to_emails'])
            msg['Subject'] = f"Task Notification: {event}"

            body = f"""
            Event: {event}
            Data: {json.dumps(data, indent=2)}
            """
            msg.attach(MIMEText(body, 'plain'))

            with smtplib.SMTP(config['smtp_server'], config['smtp_port']) as server:
                server.starttls()
                server.login(config['smtp_user'], config['smtp_password'])
                server.send_message(msg)
        except Exception as e:
            logger.error(f"Email notification failed: {str(e)}") 